package com.dzl.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.dzl.cloud.dao.UserMapper;
import com.dzl.cloud.dto.LogMessageDTO;
import com.dzl.cloud.dto.LoginDTO;
import com.dzl.cloud.dto.UpdateUserDTO;
import com.dzl.cloud.entity.User;


import com.dzl.cloud.exception.CustomException;
import com.dzl.cloud.feign.PermissionFeignClient;
import com.dzl.cloud.producer.UserLogService;
import com.dzl.cloud.service.UserService;
import com.dzl.cloud.util.JwtUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 光的代言人
 */
@Slf4j
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private PermissionFeignClient permissionFeignClient;

    @Autowired
    private UserLogService userLogService;


    @Override
    public User findByUsername(String username) {
        // 根据用户名查询用户（如果有实现方法的话）
        return userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }
    /**
     * 注册用户
     * @param user
     */
    @GlobalTransactional
    @Override
    public void registerUser(User user, HttpServletRequest request) {
        // 1.检查用户名是否已存在
        User existingUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (existingUser != null) {
            // 用户名已存在，返回错误响应
            throw new CustomException(401, "用户名已存在!");
        }
        // 2.对密码进行加密,注册用户消息
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);
        user.setGmtCreate(new java.util.Date());
        userMapper.insert(user);
//        int i=22/0;
        // 3.RPC 调用权限服务，绑定默认角色（普通用户）
        permissionFeignClient.bindDefaultRole(user.getUserId());
        // 4.发送 MQ 日志
        LogMessageDTO message = new LogMessageDTO();
        message.setUserId(user.getUserId());
        message.setAction("USER_REGISTER");
        message.setIp(getClientIp(request));
        message.setDetail("用户【"+user.getUserId()+"】 注册成功!");
        userLogService.sendLog(message);

    }
    // 获取客户端IP（AI生成）
    private String getClientIp(HttpServletRequest request) {
        // 获取X-Forwarded-For头信息，如果有多个IP，取第一个
        String ip = request.getHeader("X-Forwarded-For");

        // 如果是通过负载均衡或代理服务器访问，X-Forwarded-For可能有多个IP
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 获取代理服务器传来的IP
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 获取通过HTTP请求的客户端IP
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 获取请求来源IP
            ip = request.getRemoteAddr();
        }
        // 如果有多个IP，X-Forwarded-For会以逗号分隔，返回第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        // 如果获取到的 IP 是回环地址（0:0:0:0:0:0:0:1），处理为 127.0.0.1 或者其他默认值
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            // 你可以选择返回 "localhost" 或其他默认值
            ip = "127.0.0.1";
        }

        return ip;
    }


    /**
     * 用户登录
     * @param request
     * @return
     */
    @Override
    public User login(LoginDTO request, HttpServletRequest request2) {
        String username = request.getUsername();
        String password = request.getPassword();
        // 根据用户名查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            throw new CustomException(401, "用户名或密码错误!");
        }
        // 发送MQ日志
        LogMessageDTO message = new LogMessageDTO();
        message.setUserId(user.getUserId());
        message.setAction("USER_LOGIN");
        message.setIp(getClientIp(request2));
        message.setDetail("用户【"+user.getUserId()+"】 登录成功!");
        userLogService.sendLog(message);
        return user;
    }

    /**
     * 根据用户id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public User findById(Long userId, Long currentUserId) {
        // 解析token 获取当前用户id
//        Long currentUserId = JwtUtils.getUserIdFromToken(token);
        // 权限校验
        String roleCode = getUserRoleCode(currentUserId);
        System.out.println("------------------");
        System.out.println("当前用户角色为："+roleCode);
        if (!checkPermission(roleCode, userId, currentUserId)) {
            throw new CustomException(403, "你没有权限访问改用户信息！");
        }

        return userMapper.selectById(userId);
    }
    /**
     * 根据用户角色更新用户信息
     * @param userId
     * @param request
     */
    @Override
    public void updateUserWithPermission(Long userId, UpdateUserDTO request, Long currentUserId,HttpServletRequest request2) {
        // 解析token 获取当前用户id
//        Long currentUserId = JwtUtils.getUserIdFromToken(token);
        // 权限校验
        String roleCode = getUserRoleCode(currentUserId);
        if (!checkPermission(roleCode, userId, currentUserId)) {
            throw new CustomException(407, "你没有权限修改该用户信息！");
        }
        User user=new User();
        user.setUserId(userId);
//        user.setUsername(request.getUsername());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        // 发送MQ 日志
        LogMessageDTO message = new LogMessageDTO();
        message.setUserId(currentUserId);
        message.setAction("UPDATE_"+getUserRoleCode(userId).toUpperCase());
        message.setIp(getClientIp(request2));
        message.setDetail("修改用户【"+userId+"】的信息！");
        userLogService.sendLog(message);
        userMapper.updateById(user);
    }

    // 检查权限
    private boolean checkPermission(String roleCode, Long targetUserId, Long currentUserId) {
        // 权限校验逻辑
        if ("super_admin".equals(roleCode)) {
            return true; // 超管可以访问所有
        } else if ("admin".equals(roleCode)) {
            // 管理员可以修改自己
            if (currentUserId.equals(targetUserId)){
                return true;
            }
            // 管理员可以访问普通用户
            String targetRole = getUserRoleCode(targetUserId);
            return "user".equals(targetRole);
        } else {
            // 普通用户只能访问自己
            return currentUserId.equals(targetUserId);
        }
    }
    // 查询用户角色编码
    public String getUserRoleCode(Long userId) {
        return permissionFeignClient.getUserRoleCode(userId);
    }

    @Override
    public void updateUser(Long userId, User user) {
        userMapper.updateById(user);
    }

    /**
     * 重置密码
     * @param userId
     * @param newPassword
     */
    @Override
    public void resetPassword(Long userId, String newPassword,Long currentUserId) {
        // 解析token 获取当前用户id
//        Long currentUserId = JwtUtils.getUserIdFromToken(token);
        // 权限校验
        String roleCode = getUserRoleCode(currentUserId);
        if (!checkPermission(roleCode, userId, currentUserId)) {
            throw new CustomException(406, "你并无此权限重置该用户密码！！");
        }
        newPassword = passwordEncoder.encode(newPassword);
        userMapper.resetPassword(userId, newPassword);
    }
    /**
     * 获取用户列表
     * @return
     */
    @Override
    public List<User> getUserListWithPermission(Long currentUserId) {
        // 解析token 获取当前用户id
//        Long currentUserId = JwtUtils.getUserIdFromToken(token);

        // 权限校验
        String roleCode = getUserRoleCode(currentUserId);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        System.out.println("-----------");
        System.out.println("当前用户角色：{}"+roleCode);
        log.debug("当前用户角色：{}", roleCode);
        if("user".equals(roleCode)){
            // 只能查询自己
            queryWrapper.eq(User::getUserId, currentUserId);
        } else if ("admin".equals(roleCode)) {
            List<Long> userIds = permissionFeignClient.getUserIdsByRole("user");
            if (userIds.isEmpty()){}
            queryWrapper.in(User::getUserId, userIds);
        } else if ("super_admin".equals(roleCode)) {
            // 超管可以访问所有
        }
        else {
            throw new CustomException(400, "未知角色，没有查询权限！");
        }
        return userMapper.selectList(queryWrapper);

    }
}
